﻿using EventMgrLib;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;
using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace demo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 存储全局变量字段
        /// </summary>
        private ConcurrentDictionary<string, VarInfo> _vars = new ConcurrentDictionary<string, VarInfo>();

        public Flow flow { get; set; } = new Flow() { Name="默认"};

        private void MainForm_Load(object sender, EventArgs e)
        {
            FlowsMgr.Ins.LoadFLows();
            Flow model = FlowsMgr.Ins.Flows.FirstOrDefault(t => t.Name == "默认");
            if (model!=null)
            {
                flow = model;
            }
            canvas1.comboBox = comboBox1;
            canvas1.Import(flow);            
            ToolMgr.Ins.LoadTools();
            EventMgr.Ins.GetEvent<DebugMessage>().Subscribe(ShowMessage);
            if (GlobalVars.Ins.Vars.ContainsKey(GlobalVars.FlowVars))
            {
                _vars = GlobalVars.Ins.Vars[GlobalVars.FlowVars];
            }
            

            #region  dataGridView控件设置

            SetGrid();

            RefreshData();

            #endregion

            #region 树形图控件属性设置

            ShowFlows();


            treeView1.Nodes.Clear();
            var groups = ToolMgr.Ins.Tools.Select(tool => tool.Group).ToList().Distinct().ToList();

            foreach (var groupName in groups)
            {
                TreeNode gpNode = new TreeNode()
                {
                    Text = string.IsNullOrEmpty(groupName) ? "Default" : groupName
                };

                foreach (var tool in ToolMgr.Ins.Tools)
                {
                    if (tool.Group == groupName)
                    {
                        TreeNode toolNode = new TreeNode(tool.ItemName);
                        
                        gpNode.Nodes.Add(toolNode);
                    }
                }

                treeView1.Nodes.Add(gpNode);
            }
            
            treeView1.ExpandAll();
            
            
            

            #endregion


        }

        /// <summary>
        /// 设置控件属性
        /// </summary>
        private void SetGrid()
        {
            dataGridView.AutoGenerateColumns = false;//该属性设置可以只显示创建的字段
            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView.RowHeadersVisible = false;
            dataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView.AllowUserToAddRows = false;
            dataGridView.MultiSelect = false;
            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            
            
        }

        private void ShowFlows()
        {
            treeView2.Nodes.Clear();
            var groups = FlowsMgr.Ins.Flows.Select(flow => flow.Group).ToList().Distinct().ToList();
            foreach (var gpName in groups)
            {
                var gpNode = new TreeNode()
                {
                    Text = string.IsNullOrEmpty(gpName) ? "Default" : gpName,
                    ImageIndex = 0,
                    SelectedImageIndex = 0,
                };

                foreach (var flow in FlowsMgr.Ins.Flows)
                {
                    if (flow.Group != gpName) continue;
                    var flowNode = new TreeNode(flow.Name)
                    {
                        ImageIndex = 1,
                        SelectedImageIndex = 1,
                    };
                    gpNode.Nodes.Add(flowNode);
                }

                treeView2.Nodes.Add(gpNode);
            }
            treeView2.ExpandAll();
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private void RefreshData()
        {
            var bs = new BindingSource();            
            bs.DataSource = _vars.Values;
            dataGridView.DataSource = bs;
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            
            FlowsMgr.Ins.SaveFlows();
        }

        private void 增加变量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var varInfo = new VarInfo();
            retry:
            string str = Interaction.InputBox("请输入全局变量的名字", "命名", "在这里输入", -1, -1);
            if (_vars.ContainsKey(str))
            {
                MessageBox.Show($"对象[{str}]已存在,请重新输入一个对象名称");
                goto retry;
            }
            varInfo.Name = str;
            _vars.TryAdd(varInfo.Name, varInfo);
            RefreshData();
        }

        private void 删除变量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow?.DataBoundItem is VarInfo par)
            {
                _vars.TryRemove(par.Name, out var varInfo);
                RefreshData();
            }
        } 

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView.CurrentRow?.DataBoundItem is VarInfo par)
            {
                if (propertyGrid1.SelectedObject == par)
                {
                    propertyGrid1.Refresh();
                }
                else
                {
                    propertyGrid1.SelectedObject = par;
                }
            }
           
        }

        private void 创建工具ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmCreateTool frmCreateTool = new FrmCreateTool();
            frmCreateTool.ShowDialog();
            刷新ToolStripMenuItem_Click(null,null);
        }

        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Copy);
        }

        private void 删除工具ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes==MessageBox.Show($"是否将工具[{treeView1.SelectedNode.Text}]放入回收站?"," ",MessageBoxButtons.YesNo))
            {
                string filePath = $"{ToolMgr.Ins.ToolDirPath}{treeView1.SelectedNode.Text}.tool";
                Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(filePath, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                treeView1.SelectedNode.Remove();
                ToolMgr.Ins.LoadTools();
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            var groups = ToolMgr.Ins.Tools.Select(tool => tool.Group).ToList().Distinct().ToList();

            foreach (var groupName in groups)
            {
                TreeNode gpNode = new TreeNode()
                {
                    Text = string.IsNullOrEmpty(groupName) ? "Default" : groupName
                };

                foreach (var tool in ToolMgr.Ins.Tools)
                {
                    if (tool.Group == groupName)
                    {
                        TreeNode toolNode = new TreeNode(tool.ItemName);

                        gpNode.Nodes.Add(toolNode);
                    }
                }

                treeView1.Nodes.Add(gpNode);
            }

            treeView1.ExpandAll();
        }

        private void 创建流程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string groupName =Interaction.InputBox("请输入分组名称", "命名", "在这里输入", -1, -1);             
            string newFlowName = Interaction.InputBox("请输入流程名称", "命名", "在这里输入", -1, -1); ;            
            if (FlowsMgr.Ins.Flows.Any(flow => flow.Name == newFlowName))
            {
                MessageBox.Show($"{newFlowName}已存在");
                return;
            }
            flow.Name = newFlowName;
            flow.Group = groupName;
            ShowFlows();
        }

        private void 删除流程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var node = treeView2.SelectedNode;
            if (node.Nodes.Count > 0) return;
            var item = FlowsMgr.Ins.Flows.Find(flow => flow.Name == treeView2.SelectedNode.Text);
            if (item == null) return;
            if (UIMessageBox.ShowAsk($"是否将流程{item.Name}放入回收站?"))
            {
                string filePath = $"{FlowsMgr.Ins.FlowsPath}{item.Name}.flow";
                if (File.Exists(filePath))
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(filePath, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                    FlowsMgr.Ins.Flows.Remove(item);
                    flow = new Flow() { Name = "默认" };
                    canvas1.comboBox.Items.Clear();
                    canvas1.Import(flow);
                    ShowFlows();
                }
            }
        }

        private void treeView2_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            var findFlow = FlowsMgr.Ins.Flows.Find(flow => flow.Name == e.Node.Text);
            if (findFlow != null)
            {
                if (DialogResult.Yes== MessageBox.Show("是否替换当前显示流程","",MessageBoxButtons.YesNo))
                {
                    flow = findFlow;
                    canvas1.Import(flow);
                }
               
            }
        }

        private void canvas1_OnIncomingParameters(object sender, 流程图控件.IncomingParametersEventArgs e)
        {
            if (e.actionItem.IsScript)
            {
                propertyGrid1.SelectedObject =new ScriptObjectWrapper(e.actionItem);
            }
            else if (e.actionItem.IsLogic)
            {
                propertyGrid1.SelectedObject =new CustomObjectWrapper(e.actionItem);
            }
            else
            {
                
                propertyGrid1.SelectedObject = new CustomProperty(e.actionItem);
            }
            
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            canvas1.Delete();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ((ActionItem)comboBox1.SelectedItem).Site.ViewOriginPoint = ((ActionItem)comboBox1.SelectedItem).ViewOriginPoint;
        }

        private void 运行选中ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                if (canvas1._selectedEntity is ActionItem tool)
                {
                    tool?.Run();
                }

               
            });
        }

        private void 运行全部ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                canvas1.EditFLow?.Run();                
            });
        }

        #region 显示调试信息

        private void ShowMessage(string message)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ShowMessage(message)));
            }
            else
            {
                richTextBox1.AppendText($"{DateTime.Now} {message}\r");
            }

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (richTextBox1.TextLength > 10000)
            {
                richTextBox1.Clear();
            }
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.ScrollToCaret();
        }

        private void 清除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }


        #endregion

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FlowsMgr.Ins.Flows.Remove(flow);
            Flow flow1 = new Flow() { Name = "默认" };
            flow = flow1;
            FlowsMgr.Ins.Flows.Add(flow);
            canvas1.comboBox.Items.Clear();
            canvas1.Import(flow);
        }
    }
}
